package com.ruoyi.cases.utils.excel;

import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.DateUtils;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 * 生成excel视图，可用excel工具打开或者保存 由ViewController的return new ModelAndView(viewExcel, model)生成
 */
public class ExcelExportToFileUrl {

    /**
     * 创建Excel
     *
     * @param model    模板
     * @param workbook Excel属性
     * @param request  请求
     * @param response 请求
     * @throws Exception 异常
     */
    private void gotoCreateExcel(Map model, Workbook workbook, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
        SXSSFWorkbook sxssfworkbook = new SXSSFWorkbook();
        String excelName =
            model.get("fileName") + "_" + DateUtils.dateTimeNow("yyyyMMddHHmmss") + ".xls";
        String fileType = String.valueOf(model.get("fileName"));
        // 设置response方式,使执行此controller时候自动出现下载页面,而非直接使用excel打开
        response.setContentType("APPLICATION/OCTET-STREAM;charset=UTF-8");
        String agent = request.getHeader("USER-AGENT");
        /*if (null != agent && -1 != agent.indexOf("MSIE") || null != agent
                && -1 != agent.indexOf("Trident")) {// ie

            excelName = java.net.URLEncoder.encode(excelName, "UTF8");

        } else if (null != agent && -1 != agent.indexOf("Mozilla")) {// 火狐,chrome等

            excelName = new String(excelName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        }*/
        excelName = java.net.URLEncoder.encode(excelName, "UTF8");
        response.setHeader("Content-Disposition", "attachment; filename=" + excelName);
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        // 产生Excel表头
        HSSFSheet sheet = (HSSFSheet) workbook.createSheet();
        HSSFRow header = sheet.createRow(0);// 第0行
        // 产生标题列
        String[] titles = (String[]) model.get("titles");//名称
        String[] names = (String[]) model.get("names");//字段

        for (int n = 0; n < titles.length; n++) {
            header.createCell(n).setCellValue(titles[n]);
        }
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("TEXT"));//字符串
        int rowNum = 1;
        List<Map<String, String>> stuList = (List) model.get("list");
        ExcelExport.addCell(sheet, names, cellStyle, rowNum, stuList);
        OutputStream os = response.getOutputStream();
        workbook.write(os);
        os.flush();
        os.close();

    }

    /**
     * 创建Excel
     *
     * @param map                 map
     * @param httpServletRequest  请求
     * @param httpServletResponse 请求
     * @throws Exception 异常
     */
    public void buildExcelDocument(Map<String, Object> map, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws Exception {
        HSSFWorkbook workbook = new HSSFWorkbook();
        gotoCreateExcel(map, workbook, httpServletRequest, httpServletResponse);
    }
}
